package com.xiangshizhineng.tianzhangzhi.app.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xiangshizhineng.tianzhangzhi.app.common.PagingContext;
import com.xiangshizhineng.tianzhangzhi.app.common.R;
import com.xiangshizhineng.tianzhangzhi.app.common.ResultCode;
import com.xiangshizhineng.tianzhangzhi.app.common.SortingContext;
import com.xiangshizhineng.tianzhangzhi.app.dao.EventDAO;
import com.xiangshizhineng.tianzhangzhi.app.model.response.DistrictResponse;
import com.xiangshizhineng.tianzhangzhi.app.model.response.EventResponse;
import com.xiangshizhineng.tianzhangzhi.app.model.response.MesIsMaxIdResponse;
import com.xiangshizhineng.tianzhangzhi.app.model.response.UserResponse;
import com.xiangshizhineng.tianzhangzhi.app.service.DistrictService;
import com.xiangshizhineng.tianzhangzhi.app.service.EventService;
import com.xiangshizhineng.tianzhangzhi.app.service.UserService;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

import static com.xiangshizhineng.tianzhangzhi.app.utils.ConstantUtils.*;

@Service
@Slf4j
@Transactional
public class EventServiceImpl extends ServiceImpl<EventDAO, EventResponse> implements EventService {

    @Autowired
    EventDAO eventDAO;
    @Autowired
    private EventService eventService;
    @Autowired
    private UserService userService;
    @Autowired
    private DistrictService districtService;

    @Override
    public EventResponse queryDetailsById(Long id) {
        return eventDAO.queryDetailsById(id);
    }

    @Override
    public EventResponse cbEvent(Long id) {
        return eventDAO.cbEvent(id);
    }

    @Override
    public List<EventResponse> cbSelect(Map<String, Object> params, Vector<SortingContext> scs, PagingContext pc) {
        params = getUnionParams(params,scs,pc);
        List<EventResponse> resultList = eventDAO.cbSelect(params);
        return resultList;
    }

    @Override
    public int cbCount(Map<String, Object> params) {
        return eventDAO.cbCount(params);
    }

    @Override
    public int taskEventCount(Map<String, Object> params) {
        return eventDAO.taskEventCount(params);
    }

    @Override
    public List<EventResponse> taskEvent(Map<String, Object> params, Vector<SortingContext> scs, PagingContext pc) {
        params = getUnionParams(params,scs,pc);
        List<EventResponse> resultList = eventDAO.taskEvent(params);
        return resultList;
    }

    @Override
    public MesIsMaxIdResponse maxId(String userId) {
        return eventDAO.maxId(userId);
    }

    @Override
    public int cbMaxId(String userId) {
        return eventDAO.cbMaxId(userId);
    }

    private Map<String, Object> getUnionParams(@NonNull Map<String, Object> params, Vector<SortingContext> scs, PagingContext pc) {
        params.put("pc", pc);
        params.put("scs", scs);
        return params;
    }

    @Override
    public int mesCount(String userId) {
        return eventDAO.mesCount(userId);
    }

    @Override
    public R eventList(Long s,Long p,String eventName,Long eventStatusId,Boolean createTime,Long id){
        Page<EventResponse> page = new Page<>(p,s);
        UserResponse userResponse = userService.getById(id);
        if (userResponse == null){
            return R.fail(ResultCode.ERROR.getCode(),"该用户不存在");
        }
        if (TZJB_1.equals(userResponse.getTzjb())){
            Page<EventResponse> eventResponse = eventService.page(page,new QueryWrapper<EventResponse>()
                    .lambda()
                    .like(StringUtils.isNotEmpty(eventName),EventResponse::getEventName,eventName)
                    .eq(eventStatusId!=null&&eventStatusId.longValue()!=0,EventResponse::getEventStatusId,eventStatusId)
                    .orderBy(true,createTime, EventResponse::getCreateTime));
            return R.success(eventResponse);
        }else if (TZJB_2.equals(userResponse.getTzjb())){
            Page<EventResponse> eventResponse;
            if(userResponse.getTzxm().matches(".*田长制办公室.*")){
                eventResponse = eventService.page(page,new QueryWrapper<EventResponse>()
                        .lambda()
                        .like(StringUtils.isNotEmpty(eventName),EventResponse::getEventName,eventName)
                        .ne(EventResponse::getEventStatusId,RESOLVED)
                        .eq(eventStatusId!=null&&eventStatusId.longValue()!=0,EventResponse::getEventStatusId,eventStatusId)
                        .eq(EventResponse::getReviewer,id)
                        .orderBy(true,createTime, EventResponse::getCreateTime).orderByAsc(!createTime,EventResponse::getEventStatusId));
                return R.success(eventResponse);
            }
            DistrictResponse districtResponse = districtService.getOne(new QueryWrapper<DistrictResponse>()
                    .lambda()
                    .eq(StringUtils.isNotEmpty(userResponse.getXzqdm()),DistrictResponse::getCode,userResponse.getXzqdm()));
            List<DistrictResponse> districtResponses = districtService.list(new QueryWrapper<DistrictResponse>()
                    .lambda()
                    .eq(districtResponse.getId()!=null&&districtResponse.getId().longValue()!=0,DistrictResponse::getPid,districtResponse.getId()));
            List<String> a = new ArrayList<>();
            for (DistrictResponse districtRespons : districtResponses) {
                a.add(districtRespons.getCode());
            }
            List<UserResponse> b = userService.list(new QueryWrapper<UserResponse>()
                    .lambda()
                    .in(UserResponse::getXzqdm,a));
            List<Long> c = new ArrayList<>();
            for (UserResponse response : b) {
                c.add(response.getId());
            }
            eventResponse = eventService.page(page,new QueryWrapper<EventResponse>()
                    .lambda()
                    .like(StringUtils.isNotEmpty(eventName),EventResponse::getEventName,eventName)
                    .and(wrapper->wrapper.in(EventResponse::getHandler,c).or().in(EventResponse::getReportBy,c))
                    .eq(eventStatusId!=null&&eventStatusId.longValue()!=0,EventResponse::getEventStatusId,eventStatusId)
                    .ne(EventResponse::getEventStatusId,RESOLVED)
                    .orderBy(true,createTime, EventResponse::getCreateTime).orderByAsc(!createTime,EventResponse::getEventStatusId));
            return R.success(eventResponse);
        }else if (TZJB_4.equals(userResponse.getTzjb())||TZJB_3.equals(userResponse.getTzjb())){
            Page<EventResponse> eventResponse = eventService.page(page,new QueryWrapper<EventResponse>()
                    .lambda()
                    .like(StringUtils.isNotEmpty(eventName),EventResponse::getEventName,eventName)
                    .and(wrapper->wrapper.eq(EventResponse::getHandler,id).or().eq(EventResponse::getReportBy,id))
                    .eq(eventStatusId!=null&&eventStatusId.longValue()!=0,EventResponse::getEventStatusId,eventStatusId)
                    .orderBy(true,createTime, EventResponse::getCreateTime));
            List<EventResponse> list = eventResponse.getRecords();
            Iterator<EventResponse> iterator = list.iterator();
            while (iterator.hasNext()){
                EventResponse item = iterator.next();
                if (item.getHandler()!=null && !item.getHandler().equals(id)){
                    iterator.remove();
                }
            }
            return R.success(eventResponse);
        }else {
            return R.fail(ResultCode.ERROR.getCode(),"用户不存在");
        }
    }
}
